/*封装基本参数*/
var Base_puhui = {
    //统一分隔符
    separator: ",",
    //统一返回list页面方法
    list: function (options) {
        var defaults = {
            searchFormId: "searchForm",
            searchButtonId: "searchButton",
            tableId: "table_list",
            pageDivId: "table_page",
            domainName:"",//域名
            type: "get",
            data: {},
            url: null,
            multiple: true,//允许多选 默认true
            pageNum: 1, //默认当前页数
            pageSize: 10, //默认分页条数
            count: 0, //默认总条数
            htmlTemplate: null, //指定的list模板
            isContinue: true,//是否继续处理
            backFun: null ,//回调函数
            selectAllInputId:"select_all" //默认全选InputId
        };
        var opt = $.extend(defaults, options);
        opt.data.pageNum = opt.pageNum;
        opt.data.pageSize = opt.pageSize;
        var $searchButton = $("#" + opt.searchButtonId);
        var $searchForm = $("#" + opt.searchFormId) || $("body").find("form:first");
        if (isNotNull($searchForm)) {
            $.extend(opt.data, $searchForm.formDataToJson());
            //绑定button事件
            if (isNotNull($searchButton)) {
                //解除绑定事件
                $searchButton.unbind("click");
                $searchButton.on("click", function () {
                    $(this).searchButtonClick(opt);
                })
            }
        }

        $.ajax({
            url:opt.domainName + opt.url,
            type: opt.type,
            data: opt.data,
            success: function (list) {
                if (isNotNull(list.code) && list.code == 200) {
                    generateList(list, opt);
                    //分页
                    var pageContent = $("#" + opt.pageDivId);
                    $(pageContent).extendPagination({
                        totalCount: opt.count,
                        showCount: opt.pageNum,
                        limit: opt.pageSize,
                        callback: function (curr) {
                            opt.pageNum = curr;
                            Base_puhui.list(opt);
                        }
                    });

                    //回调函数
                    if (opt.backFun) {
                        eval("opt.backFun(list.data)");
                    }
                } else {
                    layer.msg(list.message || "返回异常,未返回错误信息");
                }
            }
        });
    },
    //统一页面增加修改查看方法
    operateForm: function (options) {
        var defaults = {
            requestNumber:0, //页面请求次数
            isFirstUpdate:true, //如果是修改 第一次请求detail
            isRender:true, //如果是add 阻止ajax请求渲染页面 默认渲染页面数据
            operateType: "add", //操作类型 默认增加 add  修改 update 详情 detail
            operateFormId: "operateForm", //需操作表单id
            operateButtonId: "operateButton", //需操作按钮id
            domainName:"",//域名
            type: "post", //默认请求方式
            data: {},
            operateUrls:{ //操作路径 增加 add  修改 update 详情 detail
                add:null,
                update:null,
                detail:null
            },
            url: null, //请求数据路径
            backFun: null //回调函数
        };
        var opt =  $.extend(defaults, options);

        switch (opt.operateType){
            case "update":
                opt.url = opt.operateUrls.update;
                break;
            case "detail":
                opt.url = opt.operateUrls.detail;
                break;
            case "add":
                opt.isRender = opt.requestNumber != 0;
                opt.requestNumber +=1;
                opt.url = opt.operateUrls.add;
                break;
            default:
                layer.msg("错误的操作方式");
                return false;
                break;
        }

        var $operateForm = $("#" + opt.operateFormId) || $("body").find("form:first");
        var $operateButton = $("#" + opt.operateButtonId) ;

        if(isNotNull($operateForm)){
            $.extend(opt.data, $operateForm.formDataToJson());
            //绑定button事件
            if (isNotNull($operateButton)) {
                //解除绑定事件
                $operateButton.unbind("click");
                $operateButton.on("click", function () {
                    Base_puhui.operateForm(opt);
                })
            }
        }
        opt.url = opt.isFirstUpdate && opt.operateType =="update" ?opt.operateUrls.detail:opt.url;

        if(isNotNull(opt.operateType) && opt.isRender){
            $.ajax({
                url:opt.domainName + opt.url,
                type: opt.type,
                data: opt.data,
                success: function (result) {
                    opt.isFirstUpdate =false;
                    if (isNotNull(result.code) && result.code == 200) {
                        //如果是详情或者修改 渲染页面值
                        if(opt.operateType=="detail" || opt.operateType=="update" ){
                            //对页面所有 有name属性的标签循环输出
                            $("[name]").each(function () {
                                var $this = $(this);
                                var name = $this.prop("name");
                                var data_type = $this.attr("data-type");
                                var data_fun = $this.attr("data-fun");
                                $this.val(renderValue(data_type,name,data_fun,result.data));
                            });
                        }
                        //回调函数
                        if (opt.backFun) {
                            eval("opt.backFun(result.data)");
                        }
                    } else {
                        layer.msg(list.message || "返回异常,未返回错误信息");
                    }
                }
            });
        }

    }
};

$.fn.searchButtonClick = function (opt) {
    var $this = $(this);
    $this.prop("disabled", "disabled");
    $this.html("查询中...");
    $this.css("background-color", "#666");
    setTimeout(function () {
        $this.removeAttr("disabled");
        $this.css("background-color", "#337ab7");
        $this.html("查询");
    }, 1000);
    Base_puhui.list(opt);
};

function generateList(list, opt) {
    opt.count = list.count;
    var $table = $("#" + opt.tableId) || $("body").find("table:first");
    //表头
    var $th = $table.find('th');

    if (opt.count == 0) {
        $table.after("<h4 style='width: 100px'>暂无数据！</h4>");
        opt.isContinue = false;
    } else {
        var tbody = " <tbody>";
        $(list.data).each(function (i, record) {
            tbody += $th.generateListTrByTh(record, opt);
        });
        tbody += "</tbody>";
        var $tbody = $table.find("tbody:first");
        if ($tbody) {
            $tbody.remove();
        }
        $table.append(tbody);
    }
}

$.fn.generateListTrByTh = function (record, opt) {
    var $selectAllInput = $("#"+opt.selectAllInputId);
    var selectAllDateName = $selectAllInput.attr("data-name");
    var returnTr = opt.multiple ? "<tr><td ><input name='"+selectAllDateName+"' type='checkbox'></td>" : "<tr>";
    $(this).each(function (i, th) {
        //如果多选 跳过第一个
        if (opt.multiple && i == 0) {
            return true;
        } else {
            var $listTr = $(th);
            var data_type = $listTr.attr("data-type");
            var data_name = $listTr.attr("data-name");
            var data_fun = $listTr.attr("data-fun");
            returnTr +=  "<td>" + renderValue(data_type,data_name,data_fun,record) + "</td>";
        }
    });
    return returnTr + "</tr>";
};

/*渲染返回值*/
function renderValue(dataType,dataName,dataFun,record) {
    if (isNotNull(dataType)) {
        switch (dataType) {
            case "date_00":
                return  getDate(ifNullDefaultEmptyString(record[dataName]));
                break;
        }
    } else if (isNotNull(dataFun)) {
        return eval("" + dataFun + "(record)");
    } else {
        return ifNullDefaultEmptyString(record[dataName]);
    }
}

//全选按钮操作事件
$.fn.selectAll = function (opt) {
    var $selectAllInput = $("#"+opt.selectAllInputId);
    var $table = $("#"+opt.tableId);
    var $checkInput = $table.find("input[type='checkbox']");
    $checkInput.prop("checked",$selectAllInput.is(":checked"));
    $
    generateIds($selectAllInput,$table);
};

function generateIds($selectAllInput,$table) {
    var idArr = [];
    $table.find("tbody:first").each("tr",function () {
        var input = $(this).find("td:first").find("input:first");
        input.is(":checked")?idArr.push(input.val()):"";
    })
    return $selectAllInput.val(idArr.join(","));
}



